
<script setup>
//引入ref
import { ref } from "vue";
const title = ref("");
const date = ref("");
const list = ref([]);
const id1 = ref("");
// 从本地获取list数据
list.value = JSON.parse(localStorage.getItem("list")) || [];
// 添加
const add = () => {
title.value = "";
date.value = "";
};
// 提交
const submit = () => {
if (title.value === "" || date.value === "") {
alert("请输入内容");
return;
}
console.log("add");

// 把数据添加到list中
list.value.push({
title: title.value,
date: date.value,
id: Date.now(),
});
title.value = "";
date.value = "";
//把list数据存到本地
localStorage.setItem("list", JSON.stringify(list.value));
};
// 删除
const del = (id) => {
//从list中通过过滤的方式去删除数据
list.value = list.value.filter((item) => item.id !== id);
localStorage.setItem("list", JSON.stringify(list.value));
};
// 编辑
const edit = (id) => {
id1.value = id;
//通过遍历的方式去找到当前点击的数据
list.value.forEach((item) => {
  //如果当前点击的数据的id和传过来的id相等就把当前的数据赋值给input框和date框
if (item.id === id) {
title.value = item.title;
date.value = item.date;
}
});
};
//声明一个变量handleDragStart是一个函数，接收两个参数event和key
//handleDragStart是一个拖拽事件，接收两个参数event和key
const handleDragStart = (event, key) => {
event.dataTransfer.setData("text/plain", key);
};
//声明一个变量handleDragOver是一个函数，接收一个参数event
const handleDragOver = (event) => {
event.preventDefault();
};
//声明一个变量handleDrop是一个函数，接收两个参数event和key
const handleDrop = (event, key) => {
event.preventDefault();
//获取拖拽的数据
const key1 = event.dataTransfer.getData("text/plain");
//交换数据
const temp = list.value[key];
//把list中的数据赋值给temp
list.value[key] = list.value[key1];
//把temp中的数据赋值给list
list.value[key1] = temp;
};
</script>
<template>
标题： <input type="text" v-model="title" /><br>
日期： <input type="date" v-model="date" /><br>
<button class="sub" @click="submit">提交</button><br>
<button class="ad" @click="add">添加</button><br>
    <table border="1">
  <tr>
    <th>标题</th>
    <th>日期</th>
    <th>操作</th>
  </tr>
  <div
    class="block"
    draggable="true"
    v-for="(item, key) in list"
    :key="key"
    @dragstart="handleDragStart($event, key)"
    @dragover="handleDragOver"
    @drop="handleDrop($event, key)"
  >
  <tr>
    <td>{{ item.title }}</td>
    <td>{{ item.date }}</td>
    <td>
      <button  @click="edit(item.id)">编辑</button>
      <button @click="del(item.id)">删除</button>
    </td>
  </tr>
</div>
</table>


</template>
<style>
table{
  border: 1px solid rgb(89, 86, 86);
  border-collapse: collapse;
  display: block;
  overflow: hidden;
  height: 250px;
  width: 450px;
}
input{
  margin-bottom: 30px;
}
button{
  text-align: center;
}
button.sub{
  margin-bottom: 30px;
}
button.ad{
  margin-bottom: 30px;
}
table tr th, table tr td {
  border: 1px solid #ccc;
  padding: 5px;
  text-align: center;
   width: 150px;
}

.scroll {
  height: 300px;
  overflow-y: auto;
  position: sticky;
  width: 500px;
}



</style>